package com.hdax.cart.controller;


import com.fasterxml.jackson.core.JsonProcessingException;
import com.hdax.cart.service.CartService;
import com.hdax.cart.vo.Cart;
import com.hdax.cart.vo.CartItem;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.util.List;
import java.util.concurrent.ExecutionException;

@Controller
public class CartController {

    @Autowired
    private CartService cartService;


    /**
     * 查询购物车所有选中的商品
     */
    @GetMapping("/currentUserCartItem")
    @ResponseBody
    public List<CartItem> getcurrentUserCartItem(){
        List<CartItem> userCartItems = cartService.getUserCartItems();
        return userCartItems;
    }


    /**
     * 删除购物
     */
    @GetMapping("/delItem")
    public String delItem(@RequestParam("skuId")Long skuId){
        cartService.delCartItem(skuId);
        return "redirect:http://cart.gulimall.com/cart.html";
    }

    /**
     * 修改购物车的数量
     */
    @GetMapping("/updateCount")
    public String checkNum(@RequestParam("skuId")Long skuId,@RequestParam("num")Integer num){
        cartService.changeItemCount(skuId,num);
        return "redirect:http://cart.gulimall.com/cart.html";
    }


    /**
     * 修改购物车的选中状态
     */
    @GetMapping("/checkCart")
    public String checkItem(@RequestParam("skuId") Long skuId,@RequestParam("isChecked") Integer check){
        cartService.checkItem(skuId,check);
        //修改成功，重定向到购物车
        return "redirect:http://cart.gulimall.com/cart.html";
    }


    /**
     * 获取整个购物车
     * @return
     */
    @GetMapping("/cart.html")
    public String cartListPage(Model model) throws ExecutionException, JsonProcessingException, InterruptedException {
        Cart cart=cartService.getCart();
        model.addAttribute("cartList",cart);
        return "cartList";
    }

    /**
     * 添加购物车
     */
    @GetMapping("/addToCart")
    public String addToCart(@RequestParam("skuId") Long skuId, @RequestParam("num") Integer num, RedirectAttributes redirectAttributes) throws ExecutionException, JsonProcessingException, InterruptedException {
        CartItem cartItem=cartService.addToCart(skuId,num);
        redirectAttributes.addAttribute("skuId",skuId);
        return  "redirect:http://cart.gulimall.com/addToCartSuccess.html";
    }

    @GetMapping("/addToCartSuccess.html")
    public String addToCartSuccessPage(@RequestParam("skuId")Long skuId,Model model){
        CartItem cartItem=cartService.getCartItem(skuId);
        model.addAttribute("cartItem",cartItem);
        return "success";
    }
}
